<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\model;
use think\Model;
use think\facade\Db;
class TableModel extends Model{
    const mainTableSql = 'data/tableSql/table_zhubiao.sql'; //主表SQL模板文件
    const sideTablesSql = 'data/tableSql/table_zhubiao_data.sql'; //副表SQL模板文件
    const modelTablesInsert = 'data/tableSql/model_insert.sql'; //默认字段
    const modelFieldPath = 'data/tableFieldTemp/'; //字段模板路径
    const modelFieldMemberPath = 'data/tableFieldTempMember/'; //会员字段模板路径
    protected $name = 'table';
    protected $pk = 'table_id';
    //关联model表
    public function model()
    {
        return $this->hasMany(ModelModel::class,"table_id");
    }  
    //创建数据表
    public function createTable(){
        //表前缀
        $dbPrefix = config('database.connections.mysql.prefix');
        //读取模型主表SQL模板
        $mainTableSqll = file_get_contents(base_path().self::mainTableSql);
        //副表
        $sideTablesSql = file_get_contents(base_path().self::sideTablesSql);
        //字段数据
        $modelTablesInsert = file_get_contents(base_path().self::modelTablesInsert);
        //表备注
        $zhubiao_note=$this->name;
        $fubiao_note=$this->name."-副表";
        //表前缀，表名，模型id替换
        $sqlSplit = str_replace(array('@prefix@', '@zhubiao@', '@table_id@', '@zhubiao_note@', '@fubiao_note@'), array($dbPrefix, $this->table_name, $this->table_id, $zhubiao_note, $fubiao_note), $mainTableSqll. $sideTablesSql  . $modelTablesInsert);
        $sqlSplit=str_replace("\r\n","",$sqlSplit);
        foreach(explode(";",$sqlSplit) as $sql){
            if($sql){
                Db::execute($sql);
            }
        }
    }
    //修改数据表
    public function updateTable($data){
        $info=$this->find($data["table_id"]);
        $this->update($data);
        //修改model表中的table_name
        $models=Db::name("model")->where("table_id",$data["table_id"])->select();
        foreach($models as $v){
            //更新模型表table_id
            Db::name("model")->update(array("modelid"=>$v['modelid'],"table_name"=>$data['table_name']));
            //更新栏目表里的table_id
            Db::name("cat")->where("modelid",$v['modelid'])->update(array("table_name"=>$data['table_name']));
        }
        
        //修改备注
        //表前缀
        $dbPrefix = config('database.connections.mysql.prefix')."cms_";
        //主表注释
        Db::execute("ALTER TABLE `{$dbPrefix}{$info['table_name']}` COMMENT='".$data['name']."';");    
        //副表注释
        Db::execute("ALTER TABLE `{$dbPrefix}{$info['table_name']}` COMMENT='".$info['name']."';"); 
        //检查是否更改表名了
        if ($info['table_name'] != $data['table_name'] && !empty($data['table_name'])) {                   
            //表名更改
            Db::execute("RENAME TABLE  `{$dbPrefix}{$info['table_name']}` TO  `{$dbPrefix}{$data['table_name']}` ;");
            //修改副表
            Db::execute("RENAME TABLE  `{$dbPrefix}{$info['table_name']}_data` TO  `{$dbPrefix}{$data['table_name']}_data` ;");
        }        
    }
    //创建字段的html凑得
    public function createTableFieldHtml(){
        $m_data=Db::name("table_field")->where("table_id",$this->table_id)->select();
        foreach($m_data as $rs){
            $newdata=array();
            $newdata['field_id']=$rs['field_id'];
            unset($rs['field_id']);//销毁fieldid 便于重新创建字段htmlcode
            $newdata['htmlcode']=$this->createFieldHtmlCode($rs);     
            $newdata['memberhtmlcode']=$this->createMemberFieldHtmlCode($rs);   
            Db::name("table_field")->update($newdata);
        }
    }
    /*
     * 创建字段html代码
     */
    public function createFieldHtmlCode($data){ 
        if(isset($data['field_id'])){
            $info=Db::name("table_field")->find($data['field_id']);
            //当字段类型 and 宽度 and 高度 and 默认值 未改变的时候htmlcode等于提交过来的，否则执行重新生成动作
            if(
                $data['htmlcode']
                &&$info['field']==$data['field']
                &&$info['name']==$data['name']
                &&$info['formtype']==$data['formtype']
                &&$data['formtype']!="morevalue"
                &&$info['formwidth']==$data['formwidth']
                &&$info['formheight']==$data['formheight']
                &&$info['defaultval']==$data['defaultval']
                &&$info['tips']==$data['tips']
                &&$info['imgwidth']==$data['imgwidth']
            ){
                $htmlcode=$data['htmlcode'];
            }else{
                $htmlcode=$this->FieldHtmlCodeReplace($data);
            }
        }else{
             $htmlcode=$this->FieldHtmlCodeReplace($data);
        }
        return $htmlcode;
    }
    /*
     * 创建会员投入字段html代码
     */
    public function createMemberFieldHtmlCode($data){ 
        if(isset($data['field_id'])){
            $info=Db::name("table_field")->find($data['field_id']);
            //当字段类型 and 宽度 and 高度 and 默认值 未改变的时候htmlcode等于提交过来的，否则执行重新生成动作
            if(
                $data['memberhtmlcode']
                &&$info['field']==$data['field']
                &&$info['name']==$data['name']
                &&$info['formtype']==$data['formtype']
                &&$data['formtype']!="morevalue"
                &&$info['formwidth']==$data['formwidth']
                &&$info['formheight']==$data['formheight']
                &&$info['defaultval']==$data['defaultval']
                &&$info['tips']==$data['tips']
            ){
                $htmlcode=$data['memberhtmlcode'];
            }else{
                $htmlcode=$this->FieldHtmlCodeReplace($data,1);
            }
        }else{
             $htmlcode=$this->FieldHtmlCodeReplace($data,1);
        }
        return $htmlcode;
    }    
    /*
     * 替换字段类型的代码
     * 
     */
    public function FieldHtmlCodeReplace($rs,$isMember=0){
        //获取表单类型的模板文件
        if($isMember){
            $field_temp= file_get_contents(base_path().self::modelFieldMemberPath.$rs['formtype'].".php");
        }else{
            $field_temp= file_get_contents(base_path().self::modelFieldPath.$rs['formtype'].".php");
        }
        
        //内容替换
        $field_temp=  str_replace("{modelFieldTemp_field}",$rs['field'],$field_temp);
        $field_temp=  str_replace("{tips}",$rs['tips'],$field_temp);
        $field_temp=  str_replace("{defaultval}",$rs['defaultval'],$field_temp);
        //宽度
        if($rs['formwidth']){
            $style_formwidth="width:".$rs['formwidth']."%;";
        }else{
            $style_formwidth="";
        }
        $field_temp=  str_replace("{style_formwidth}",$style_formwidth,$field_temp);
        //高度
        if($rs['formheight']){
            $style_formheight="height:".$rs['formheight']."px;";
        }else{
            $style_formheight="";
        }
        $field_temp=  str_replace("{style_formheight}",$style_formheight,$field_temp);
        //编辑器高度 宽度替换（因为编辑器只调用数值，不需要css样式）
        $field_temp=  str_replace("{imgwidth}",$rs['imgwidth'],$field_temp);
        $field_temp=  str_replace("{imgheight}",$rs['imgheight'],$field_temp);
        $field_temp=  str_replace("{formwidth}",$rs['formwidth']."%",$field_temp);
        $field_temp=  str_replace("{formheight}",$rs['formheight']?$rs['formheight']:500,$field_temp);
        //图片上传高度宽度替换
        
        //checkbox radio select选项替换
        $checkbox_option="";
        if($rs['formtype']=="checkbox"||$rs['formtype']=="radio"||$rs['formtype']=="select"||$rs['formtype']=="selects"){
            if($rs['defaultval']){
                $defaultval=explode("\r\n",$rs['defaultval']);                
                foreach($defaultval as $v){                    
                    $dufault_arr=explode(":",$v);
                    $option_arr=explode("==",$dufault_arr[0]);                    
                    $select_checked=$dufault_arr[1]=="default"?'{$r?"":"selected"}':"";//select 默认选择中的
                    $checked_default=$dufault_arr[1]=="default"?'{$r?"":"checked"}':"";//checked radio 默认选择中的
                    $option_name=trim($option_arr[0]);//字段名称
                    $option_value=trim($option_arr[1]==""?$option_arr[0]:$option_arr[1]);//字段值 为空时=名称
                    if($rs['formtype']=="checkbox"){
                        $checkbox_option.='<input type="checkbox"  name="'.$rs['field'].'[]" value="'.$option_value.'" title="'.$option_name.'" {:strstr($r[\''.$rs['field'].'\'],\'|'.$option_value.'|\')?"checked":""} '.$checked_default.'/></label>';
                    }
                    if($rs['formtype']=="radio"){
                        $checkbox_option.='<input type="radio"  name="'.$rs['field'].'" value="'.$option_value.'" title="'.$option_name.'" {:$r[\''.$rs['field'].'\']==\''.$option_value.'\'?"checked":""} '.$checked_default.'/></label>';                        
                    }  
                    if($rs['formtype']=="select"){
                        $checkbox_option.='<option value="'.$option_value.'" {$r[\''.$rs['field'].'\']==\''.$option_value.'\'?"selected":""} '.$select_checked.'>'.$option_name.'</option>';
                    }
                    if($rs['formtype']=="selects"){
                        $checkbox_option.='<option value="'.$option_value.'" {:strstr($r[\''.$rs['field'].'\'],\'|'.$option_value.'|\')?"selected":""} '.$select_checked.'>'.$option_name.'</option>';                        
                    }                      
                    
                }                
            }
            $field_temp=  str_replace("{select_option}",$checkbox_option,$field_temp);
        }
        //多值字段替换
        if($rs['formtype']=="morevalue"){
            $morevalue_name=$rs["morevalue_name"];//字段名
            $morevalue_type=$rs["morevalue_type"];//字段类型
            $morevalue_defaultvalue=$rs["morevalue_defaultvalue"];//默认值
            $morevalue_width=$rs["morevalue_width"];//宽度
            $name_str="";$form_str="";$form_str_js="";
            foreach($morevalue_name as $k=>$v){
                //标题
                $morevalue_width[$k]=intval($morevalue_width[$k]);
                $name_str.='<th style="width:'.($morevalue_width[$k]?$morevalue_width[$k]:10).'%">'.$morevalue_name[$k].'<input type="hidden" name="'.$rs['field'].'_morevalue_len[]" placeholder="我只是用于在保存信息的时候用来判断一共有几个morevalue字段的"></th>';
                //字段表单--------------
                //下拉菜单
                if($morevalue_type[$k]=="select"){
                    $form_str.='<td class="morevalue_select"><select class="layui-input" lay-ignore name="'.$rs['field'].'_'.$k.'[]">';
                    $form_str_js.='<td class="morevalue_select"><select class="layui-input" lay-ignore name="'.$rs['field'].'_'.$k.'[]">';
                    $defaultval=explode("\r\n",$morevalue_defaultvalue[$k]);
                    foreach($defaultval as $v2){
                        $dufault_arr=explode(":",$v2);
                        $option_arr=explode("==",$dufault_arr[0]);                    
                        $select_checked=$dufault_arr[1]=="default"?'<?=$r?"":"selected"?>':"";//select 默认选择中的
                        $checked_default=$dufault_arr[1]=="default"?'<?=$r?"":"checked"?>':"";//checked radio 默认选择中的
                        $option_name=trim($option_arr[0]);//字段名称
                        $option_value=trim($option_arr[1]==""?$option_arr[0]:$option_arr[1]);//字段值 为空时=名称                        
                        $form_str.='<option value="'.$option_value.'" <?=$vs[\''.$k.'\']==\''.$option_value.'\'?"selected":""?> '.$select_checked.'>'.$option_name.'</option>';
                        $form_str_js.='<option value="'.$option_value.'" '.$select_checked.'>'.$option_name.'</option>';
                    }
                    $form_str.='</td>';
                    $form_str_js.='</td>';
                }
                //图片
                else if($morevalue_type[$k]=="image"){
                    $form_str.='<td class="morevalue_image"><input value="<?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?>" id="'.$rs['field'].'_'.$k.'_<?=$k?>" name="'.$rs['field'].'_'.$k.'[]"><a class="layui-btn layui-btn-sm"  onClick="selectfile(\''.$rs['field'].'_'.$k.'_<?=$k?>\',\'\',\'img\',\'\',\'\')"><i class="layui-icon">&#xe681;</i></a><a class="layui-btn layui-btn-sm"  onClick="morevaluePreImg(\''.$rs['field'].'_'.$k.'_<?=$k?>\')"><i class="layui-icon">&#xe615;</i></a></td>';
                    $form_str_js.='<td class="morevalue_image"><input value="'.$morevalue_defaultvalue[$k].'" id="randImgId" name="'.$rs['field'].'_'.$k.'[]"><a class="layui-btn layui-btn-sm" onClick="selectfile(\'randImgId\',\'\',\'img\',\'\',\'\')"><i class="layui-icon">&#xe681;</i></a><a class="layui-btn layui-btn-sm" onClick="morevaluePreImg(\'randImgId\')"><i class="layui-icon">&#xe615;</i></a></td>';
                }
                //文件
                else if($morevalue_type[$k]=="file"){
                    $form_str.='<td class="morevalue_file"><input value="<?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?>" id="'.$rs['field'].'_'.$k.'_<?=$k?>" name="'.$rs['field'].'_'.$k.'[]"><a class="layui-btn layui-btn-sm" onClick="selectfile(\''.$rs['field'].'_'.$k.'_<?=$k?>\',\'\',\'file\',\'\',\'\')"><i class="layui-icon">&#xe681;</i></a><a class="layui-btn layui-btn-sm"  onClick="morevaluePreFile(\''.$rs['field'].'_'.$k.'_<?=$k?>\')"><i class="layui-icon">&#xe615;</i></a></td>';
                    $form_str_js.='<td class="morevalue_file"><input value="'.$morevalue_defaultvalue[$k].'" id="randFileId" name="'.$rs['field'].'_'.$k.'[]"><a class="layui-btn layui-btn-sm" onClick="selectfile(\'randFileId\',\'\',\'file\',\'\',\'\')"><i class="layui-icon">&#xe681;</i></a><a class="layui-btn layui-btn-sm" onClick="morevaluePreFile(\'randFileId\')"><i class="layui-icon">&#xe615;</i></a></td>';                   
                }
                //视频
                else if($morevalue_type[$k]=="video"){
                    $form_str.='<td class="morevalue_video"><input class="layui-input" value="<?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?>" id="'.$rs['field'].'_'.$k.'_<?=$k?>" name="'.$rs['field'].'_'.$k.'[]"><a class="layui-btn layui-btn-sm" onClick="selectfile(\''.$rs['field'].'_'.$k.'_<?=$k?>\',\'\',\'video\',\'\',\'\')"><i class="layui-icon">&#xe681;</i></a><a class="layui-btn layui-btn-sm"  onClick="morevaluePreVideo(\''.$rs['field'].'_'.$k.'_<?=$k?>\')"><i class="layui-icon">&#xe615;</i></a></td>';
                    $form_str_js.='<td class="morevalue_video"><input class="layui-input" value="'.$morevalue_defaultvalue[$k].'" id="randVideoId" name="'.$rs['field'].'_'.$k.'[]"><a class="layui-btn layui-btn-sm" onClick="selectfile(\'randVideoId\',\'\',\'video\',\'\',\'\')"><i class="layui-icon">&#xe681;</i></a><a class="layui-btn layui-btn-sm" onClick="morevaluePreVideo(\'randVideoId\')"><i class="layui-icon">&#xe615;</i></a></td>';                           
                }  
                //文本域
                else if($morevalue_type[$k]=="textarea"){
                    $form_str.='<td class="morevalue_textarea"><textarea onclick="moreBigTextarea(this,2)" class="layui-input" name="'.$rs['field'].'_'.$k.'[]"><?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?></textarea></td>';
                    $form_str_js.='<td class="morevalue_textarea"><textarea onclick="moreBigTextarea(this,2)" class="layui-input" name="'.$rs['field'].'_'.$k.'[]">'.$morevalue_defaultvalue[$k].'</textarea></td>';
                //文本框                  
                }else {                
                    $form_str.='<td class="morevalue_input"><input class="layui-input" placeholder="" value="<?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?>" name="'.$rs['field'].'_'.$k.'[]"></td>';
                    $form_str_js.='<td class="morevalue_input"><input class="layui-input" placeholder="" value="'.$morevalue_defaultvalue[$k].'" name="'.$rs['field'].'_'.$k.'[]"></td>';
                }
            }
            $name_str.='<th style="width:10%">操作</th>';
            $form_str.='<td class="morevalue_button"><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_add(this,'.$rs['field'].'_form_js)"><i class="layui-icon">&#xe654;</i></a><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_del(this)"><i class="layui-icon">&#xe640;</i></a></td>';
            $form_str_js.='<td class="morevalue_button"><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_add(this,'.$rs['field'].'_form_js)"><i class="layui-icon">&#xe654;</i></a><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_del(this)"><i class="layui-icon">&#xe640;</i></a></td>';        
            $field_temp=  str_replace("{morevalue_fieldName}",$name_str,$field_temp);
            $field_temp=  str_replace("{morevalue_fieldForm}",$form_str,$field_temp);
            $field_temp=  str_replace("{morevalue_fieldFormJs}",str_replace("'","\'",$form_str_js),$field_temp);//替换formjs，用于多值字段增加的js
        }        
        
        return $field_temp;
    } 
    /**
     * 删除表
     * @param string $tablename 不带表前缀的表名
     * @return type
     */
    public function drop_table($tablename){
        if (table_exists($tablename)) {
            $tablename = config('database.connections.mysql.prefix'). $tablename;
            return Db::execute("DROP TABLE $tablename");
        }
    }    
}
